package com.laigewan.laigewanaccessibilityservice;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * 每当窗口有活动时，就会有消息回调到onAccessibilityEvent()方法中，因此所有的逻辑都是从这里开始的。
 * 首先我们可以通过传入的AccessibilityEvent参数来获取当前事件的类型，事件的种类非常多，
 * 但是我们只需要监听
 * TYPE_WINDOW_CONTENT_CHANGED
 * 和
 * TYPE_WINDOW_STATE_CHANGED
 * 这两种事件就可以了，因为在整个安装过程中，这两个事件必定有一个会被触发。
 *
 * 当然也有两个同时都被触发的可能，那么为了防止二次处理的情况，这里我们使用了一个Map来过滤掉重复事件。
 */
public class LGWAccessibilityServiceTemp extends AccessibilityService {

    Map<Integer, Boolean> handledMap = new HashMap<>();

    public LGWAccessibilityServiceTemp() {
    }

    private static final int DELAY_PAGE = 300; // 页面切换时间
    private final Handler mHandler = new Handler();


    @Override
    protected void onServiceConnected() {
        // LogUtils.i("onServiceConnected: ");
        // Toast.makeText(this, getString(R.string.aby_label) + "开启了", Toast.LENGTH_LONG).show();
        // 服务开启，模拟两次返回键，退出系统设置界面（实际上还应该检查当前UI是否为系统设置界面，但一想到有些厂商可能篡改设置界面，懒得适配了...）

        // performGlobalAction(GLOBAL_ACTION_BACK);
        // performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS);
        // performGlobalAction(GLOBAL_ACTION_POWER_DIALOG);
        // performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
        // performGlobalAction(GLOBAL_ACTION_RECENTS);
        // Intent intent =  new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // startActivity(intent);

        performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS);   // 推荐，如果不可以 使用下面的

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                performGlobalAction(GLOBAL_ACTION_BACK);
            }
        }, DELAY_PAGE);
    }

    @Override
    public void onDestroy() {
        // LogUtils.i("AutoInstallService -- onDestroy: ");
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        AccessibilityNodeInfo nodeInfo = event.getSource();
        if (nodeInfo != null) {
            int eventType = event.getEventType();
            if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED ||
                    eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                if (handledMap.get(event.getWindowId()) == null) {
                    boolean handled = iterateNodesAndHandle(nodeInfo);
                    if (handled) {
                        handledMap.put(event.getWindowId(), true);
                    }
                }
            }
        }
    }

    private boolean iterateNodesAndHandle(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo != null) {
            int childCount = nodeInfo.getChildCount();
            if ("android.widget.Button".equals(nodeInfo.getClassName())) {
                String nodeContent = nodeInfo.getText().toString();
                Log.d("TAG", "content is " + nodeContent);
                if ("安装".equals(nodeContent)
                         // || "完成".equals(nodeContent)
                         || "打开".equals(nodeContent)
                         || "确定".equals(nodeContent)
                        ) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    return true;
                }
            }else if ("android.widget.TextView".equals(nodeInfo.getClassName())) {
                String nodeContent = nodeInfo.getText().toString();
                Log.d("TAG", "content is " + nodeContent);
                if ("安装".equals(nodeContent)
                        // || "完成".equals(nodeContent)
                        || "打开".equals(nodeContent)
                        || "确定".equals(nodeContent)
                        ) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    return true;
                }
            } else if ("android.widget.ScrollView".equals(nodeInfo.getClassName())) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
            }
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo childNodeInfo = nodeInfo.getChild(i);
                if (iterateNodesAndHandle(childNodeInfo)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onInterrupt() {
    }
}
